<script setup lang="ts">
import { providers, Contract, constants, BigNumber, FixedNumber } from 'ethers'
import DepositContractAbi from '../data/DepositContract.abi.json'
import ADDRESS from '../data/address'
import saveBlob from "save-blob"

const chosenChain = localStorage.getItem('chain') as string
const DepositContractAddress = (ADDRESS as any)[chosenChain]

const account = ref('')
const chainId = ref('')
const balanceLoaded = ref(false)
const balance = ref(0)
// const w3 = ref(null as any)
// const lastTxn = ref(localStorage.getItem('lastTxn') || '')
const lastTxn = ref('')

const connected = computed(() => account.value != '' && chainId.value != '')

const accountShort = computed(() => account.value.slice(0, 6) + '...' + account.value.slice(account.value.length - 4, account.value.length))
const networkName = computed(() => {
  return chainId.value == '0x5' ? 'Goerli' : 'Unsupported Network'
})

const deposits_data = ref(JSON.parse(localStorage.getItem('deposit_data') as string))

const connect = async () => {
  try {
    const eth = (window as any).ethereum
    const accounts = await eth.enable()
    account.value = accounts[0]
    chainId.value = eth.chainId
    const provider = new providers.Web3Provider(eth)
      ; (window as any).w3 = provider.getSigner()
    const balanceBn: BigNumber = await (window as any).w3.getBalance()
    balance.value = FixedNumber.from(balanceBn).divUnsafe(FixedNumber.from('1000000000000000000')).toUnsafeFloat()
    balanceLoaded.value = true
  }
  catch (err) {
    console.log('error while connecting', err);
  }
}

const deposit = async (i: number) => {
  try {
    const DepositContract = new Contract(DepositContractAddress, DepositContractAbi, (window as any).w3)
    const data = deposits_data.value[i]
    console.log(data);

    const tx = await DepositContract.deposit(
      '0x' + data.pubkey,
      '0x' + data.withdrawal_credentials,
      '0x' + data.signature,
      '0x' + data.deposit_data_root,
      { value: constants.WeiPerEther.mul(32) },
    )
    console.log(tx);
    localStorage.setItem('lastTxn', tx.hash)
    // lastTxn.value = tx.hash
  }
  catch (err) {
    console.log('error while depositing', err);
  }
}

const download = () => {
  const data = localStorage.getItem('deposit_data') as string
  const fileBlob = new Blob([data], { "type": "text/plain" })
  saveBlob(fileBlob, "deposit_data.json")
}
</script>

<template>
  <div class="page-send">
    <div class="card">
      <div class="title">Step (4/4): Send Transaction</div>
      

      <div v-if="lastTxn">
        <div>Transaction submited! <a class="blue" :href="`https://goerli.etherscan.io/tx/${lastTxn}`">View on etherscan</a>.</div>
      </div>
      <div v-else-if="!connected">
        <div>Your deposit information has been generated. Connect your wallet to send transaction.</div>
        <div class="btn-in-card mt-4" @click="connect">Connect</div>
      </div>
      <div class="mt-2" v-else>
        <div class="force-wrap">Your account: {{ accountShort }}</div>
        <div>Network: {{ networkName }}</div>
        <div>
          <div v-if="!balanceLoaded">
            <div>Balance: Loading...</div>
          </div>
          <div v-else>
            <div class="red" :class="{'green': balance>=32}">Balance: {{ balance.toFixed(3) }} <span>({{balance>=32?'Enough':'require 32Eth'}})</span></div>
          </div>
        </div>
        <div>
          <div class="btn-in-card mt-4" v-for="(item, index) in deposits_data" @click="deposit(index)">Deposit(Index: {{index}})</div>
        </div>
        
      </div>
    </div>

    <div class="card">
      <div class="sub">Save deposit data(Optional)</div>
      <div>Save your deposit data here, this is optional, because you can view it on block explorer after the transaction is confirmed.</div>
      <div class="btn-in-card mt-2" @click="download">Download</div>
    </div>
  </div>
</template>

<style>
.page-send {
  padding: 15px;
}

.force-wrap {
  word-break: break-all;
}
.red {
  color: red;
}
.green {
  color: green;
}
</style>